package com.wsx.rpc.comsat.fiber;

import co.paralleluniverse.fibers.Fiber;
import co.paralleluniverse.fibers.SuspendExecution;
import co.paralleluniverse.strands.SuspendableRunnable;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.LongAdder;

/**
 * @author wangshuaixin
 * @Title: com.wsx.rpc.comsat.fiber.FiberCompare
 * @Description: TODO
 * @date 2018/11/22
 */
public class FiberCompare {

    public static void main(String[] args) throws InterruptedException {
        int count = 1000;

        testPool(count);
        testFiber(count);
    }

    private static void testPool(int count) throws InterruptedException {
        final CountDownLatch latch = new CountDownLatch(count);
        ExecutorService service = Executors.newFixedThreadPool(200);
        LongAdder latency = new LongAdder();
        LongAdder counter = new LongAdder();
        AtomicInteger integer = new AtomicInteger(0);
        long start = System.currentTimeMillis();
        for (int i = 0; i < count; i++) {
            service.submit(() -> {
                try {
                    Thread.sleep(100);
                } catch (Exception e) {

                }

                latency.add(100);

                counter.add(1);
                integer.incrementAndGet();
                latch.countDown();
            });
        }

        latch.await();
        start = System.currentTimeMillis() - start;

        System.out.println("pool took :" + start + "--latency:" + (latency.longValue()/count) + "--sum:" + integer.get());

        service.shutdownNow();
    }

    private static void testFiber(int count) throws InterruptedException {
        final CountDownLatch latch = new CountDownLatch(count);
        LongAdder latency = new LongAdder();
        LongAdder counter = new LongAdder();
        AtomicInteger integer = new AtomicInteger(0);
        long start = System.currentTimeMillis();
        for (int i = 0; i < count; i++) {
            new Fiber<Void>("caller", new SuspendableRunnable() {
                @Override
                public void run() throws SuspendExecution, InterruptedException {
                    Thread.sleep(100);
                    latency.add(100);

                    counter.add(1);
                    integer.incrementAndGet();
                    latch.countDown();
                }
            }).start();
        }

        latch.await();
        start = System.currentTimeMillis() - start;

        System.out.println("fiber took :" + start + "--latency:" + (latency.longValue()/count) + "--sum:" + integer.get());

    }
}
